<template>
  <div>
    <Card>
      <tables
        ref="tables"
        editable
        searchable
        search-place="top"
        v-model="tableData"
        :columns="columns"
        :loading="loading"
        :plusSearchColumns="plusSearchColumns"
        @on-delete="handleDelete"
        @on-batch-delete="handleBatchDelete"
        @on-refresh="getData"
        @on-select="onSelect"
        @on-search="getDataOnSearch"
        @on-select-cancel="onSelectCancel"
        @on-select-all="onSelectAll"
        @on-select-all-cancel="onSelectAllCancel"
        @on-selection-change="onSelectionChange"
        @on-sort-change="onSortChange"
        @on-filter-change="onFilterChange"
        @on-create="onCreate"
        @on-update="onUpdate"
        @on-row-click="onRowClick"
        @on-row-dblclick="onRowDblclick"
        @on-expand="onExpand"
        @on-save-edit="onSaveEdit"
        />
      <div style="float: right; margin-top:10px;">
        <Page
        :total="page.total"
        :current='page.current'
        :page-size='page.pageSize'
        :page-size-opts='page_size_opts'
        @on-page-size-change="getDataByChangeSize"
        @on-change="getData"
        show-sizer />
      </div>
      <Button style="margin: 10px 0;" type="primary" @click="exportExcel">导出为Csv文件</Button>
      <!-- 详情 -->
      <Drawer title="当前用户详情" :closable="false" width="35%"  v-model="showCurrentRowFlag">
        <div class="demo-drawer-profile" v-show="Object.keys(currentRow).length > 0 ">
          <Row >
            <Col span="12">真实名称: {{ currentRow.realName }} </Col>
            <Col span="12">登录名:{{ currentRow.loginName }}</Col>
          </Row>
          <Row >
            <Col span="12">昵称: {{ currentRow.nickname }}</Col>
            <Col span="12">手机: {{ currentRow.phone }}</Col>
          </Row>
          <Row>
            <Col span="12">邮箱: {{ currentRow.email }}</Col>
            <Col span="12">创建时间: {{ currentRow.createdTime }} </Col>
          </Row>
        </div>
      </Drawer>
      <!-- 新增 或 编辑 -->
      <Drawer
      :title="drawerTitle"
      v-model="onCreateFlag"
      width="720"
      :mask-closable="false"
      :styles="styles"
      >
        <Form ref="formRef" :model="formData" :rules="ruleValidate">
            <Row :gutter="32">
                <Col span="12">
                    <FormItem label="登录名" label-position="top" prop="loginName">
                        <Input v-model="formData.loginName" placeholder="请输入登录名" />
                    </FormItem>
                </Col>
                <Col span="12">
                    <FormItem label="昵称" label-position="top" prop="nickname">
                        <Input v-model="formData.nickname" placeholder="请输入昵称">
                            <!-- <span slot="prepend">http://</span> -->
                            <!-- <span slot="append">.com</span> -->
                        </Input>
                    </FormItem>
                </Col>
            </Row>
            <Row :gutter="32">
                <Col span="12">
                  <FormItem label="真实名称" label-position="top" prop="realName">
                    <Input v-model="formData.realName" placeholder="请输入真实名称" />
                  </FormItem>
                </Col>
                <Col span="12">
                    <FormItem label="手机" label-position="top" prop="phone">
                      <Input v-model="formData.phone" placeholder="请输入手机" />
                    </FormItem>
                </Col>
            </Row>
            <Row :gutter="32">
                <Col span="12">
                    <FormItem label="部门" label-position="top" prop="deptCode">
                      <!-- <Input v-model="formData.deptCode" placeholder="请输入部门" /> -->
                      <TreeSelectForForm
                      :data="deptList"
                      :labelKey="labelKey"
                      :idKey="idKey"
                      v-model="formData.deptCode"
                       />
                    </FormItem>
                </Col>
                <Col span="12">
                    <FormItem label="岗位" label-position="top" prop="position">
                      <Select v-model="formData.positionCode">
                          <Option v-for="item in selectPostionList" :value="item.value" :key="item.value">{{ item.label }}</Option>
                      </Select>
                    </FormItem>
                </Col>
            </Row>
            <Row :gutter="32">
                <Col span="12">
                    <FormItem label="邮箱" label-position="top" prop="email">
                      <Input v-model="formData.email" autocomplete="off" placeholder="请输入邮箱地址" />
                    </FormItem>
                </Col>
                <Col span="12">
                    <FormItem label="初始密码" label-position="top" prop="password">
                      <Input v-model="formData.password" value="origin" type="password" clearable placeholder="请输入初始用户登录密码" />
                    </FormItem>
                </Col>
            </Row>
            <Row :gutter="32">
                <Col span="24">
                    <FormItem label="角色" label-position="top" prop="role">
                      <CheckboxGroup v-model="formData.roleCode">
                        <Checkbox v-for="role in roleList" :key="role.uuid" :label="role.code">{{ role.roleName }}</Checkbox>
                      </CheckboxGroup>
                    </FormItem>
                </Col>
            </Row>
            <FormItem label="个人描述" label-position="top" prop="description">
                <Input type="textarea" v-model="formData.description" :rows="4" placeholder="请输入个人描述" />
            </FormItem>
        </Form>
        <div class="demo-drawer-footer">
            <Button style="margin-right: 8px" @click="onCreateFlag = false">取消</Button>
            <Button type="primary" v-if="operation === 'create'" @click="doCreate">提交</Button>
            <Button type="primary" v-if="operation === 'edit'" @click="doUpdate">提交</Button>
        </div>
      </Drawer>
    </Card>
  </div>
</template>

<script>
import Tables from '_c/tables'
import { getUsers, addUser, updateUser, deleteUser, deleteUsers } from '@/api/base/user'
import TreeSelectForForm from './tree-select-for-form'
import DeptApi from '@/api/base/dept'
import PositionApi from '@/api/base/position'
import RoleApi from '@/api/base/role'

export default {
  name: 'UserTable',
  props: {
    deptCode: {
      type: String,
      default: () => {
        return ''
      }
    }
  },
  components: {
    Tables,
    TreeSelectForForm
  },
  data () {
    return {
      columns: [
        { type: 'selection', width: 60, key: 'handle', align: 'center' },
        { title: '登录名', key: 'loginName', sortable: true },
        { title: '昵称', key: 'nickname', sortable: true },
        { title: '邮箱', key: 'email', editable: true },
        { title: '部门', key: 'deptName' },
        { title: '岗位', key: 'positionName' },
        { title: '电话', key: 'phone', editable: true },
        { title: '创建时间', key: 'createdTime' },
        { title: '更新时间', key: 'updatedTime' },
        {
          title: '操作',
          key: 'handle',
          width: 220,
          options: ['delete', 'detail'],
          button: [
            (h, params, vm) => {
              return h('Button', {
                props: {
                  type: 'text',
                  ghost: true
                },
                on: {
                  'click': () => {
                    this.onUpdate(params.row)
                  }
                }
              }, [
                h('Icon', {
                  props: {
                    type: 'md-build',
                    size: 18,
                    color: '#000000'
                  }
                })
              ])
            },
            (h, params, vm) => {
              return h('Button', {
                props: {
                  type: 'text',
                  ghost: true
                },
                on: {
                  'click': () => {
                    this.showCurrentRow(params.row)
                  }
                }
              }, [
                h('Icon', {
                  props: {
                    type: 'md-more',
                    size: 18,
                    color: '#000000'
                  }
                })
              ])
            }
          ]
        }
      ],
      // 高级查询默认语句测试
      plusSearchColumns: [
        {
          row: 1,
          list: [
            {
              type: 'input',
              name: 'realName',
              label: '真实姓名',
              placeholder: '真实姓名',
              default: ''
            },
            {
              type: 'input',
              name: 'nickname',
              label: '昵称',
              placeholder: '昵称',
              default: ''
            },
            {
              type: 'datetime', // 时间区间，使用两个默认值, 一个默认开始时间  一个结束时间
              name: 'createdTime',
              label: '创建时间',
              placeholderStart: '开始时间',
              placeholderEnd: '结束时间',
              default: '',
              default2: ''
            }
            // {
            //   type: 'select', // 表单类型
            //   name: 'Sel', // 对应表单的字段名
            //   label: 'Sel', // 标签
            //   placeholder: '填写Sel', // 如名
            //   default: '1', // 默认值
            //   options: [
            //     {
            //       key: 'one',
            //       val: '1'
            //     },
            //     {
            //       key: 'two',
            //       val: '2'
            //     }
            //   ]
            // }
          ]
        },
        {
          row: 2,
          list: [
            {
              type: 'radio', // 多选一
              name: 'status',
              label: '启禁用',
              placeholder: '启禁用',
              default: 1,
              options: [
                {
                  key: '启用',
                  val: 1
                },
                {
                  key: '禁用',
                  val: 0
                }
              ]
            }
            // {
            //   type: 'checkbox', // 多选一
            //   name: 'checkbox',
            //   label: 'checkbox',
            //   placeholder: 'checkbox',
            //   default: ['1'],
            //   options: [
            //     {
            //       key: 'one',
            //       val: '1'
            //     },
            //     {
            //       key: 'two',
            //       val: '2'
            //     }
            //   ]
            // }
          ]
        }
      ],
      tableData: [],
      // 分页显示数组
      page_size_opts: [10, 20, 30, 50],
      page: {
        current: 1,
        pageSize: 10,
        total: 0,
        totalPage: 0
      },
      selectedRows: [],
      currentRow: {},
      showCurrentRowFlag: false,
      onCreateFlag: false,
      styles: {
        height: 'calc(100% - 55px)',
        overflow: 'auto',
        paddingBottom: '53px',
        position: 'static'
      },
      loading: false,
      drawerTitle: '',
      operation: 'create',
      formData: {
        realName: '',
        nickname: '',
        loginName: '',
        phone: '',
        email: '',
        password: 'origin',
        deptCode: '', // 部门code
        roleCode: [],
        description: ''
      },
      ruleValidate: {
        realName: [
          { required: true, message: 'The realName cannot be empty', trigger: 'blur' }
        ],
        nickname: [
          { required: true, message: 'The nickname cannot be empty', trigger: 'blur' }
        ],
        loginName: [
          { required: true, message: 'The loginName cannot be empty', trigger: 'blur' }
        ],
        email: [
          { required: true, message: 'Mailbox cannot be empty', trigger: 'blur' },
          { type: 'email', message: 'Incorrect email format', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: 'The phone cannot be empty', trigger: 'blur' }
        ],
        password: [
          { required: true, message: 'The password cannot be empty', trigger: 'blur' }
        ],
        description: [
          { type: 'string', min: 10, message: 'Introduce no less than 10 words', trigger: 'blur' }
        ]
      },
      // 部门列表使用的字段
      deptList: [],
      idKey: 'code',
      labelKey: 'deptName',
      // 岗位列表
      positionList: [],
      selectPostionList: [],
      // 角色列表
      roleList: []
      // selectRoleList: []
    }
  },
  methods: {
    handleDelete (params) {
      const id = params.row.uuid
      this.loading = true
      deleteUser(id).then(res => {
        this.loading = false
      })
    },
    /**
     * 批量删除
     */
    handleBatchDelete () {
      if (this.selectedRows.length < 1) {
        console.error('至少选中一行')
        this.$Message.error('至少选中一行')
        return -1
      }
      let idList = []
      for (let i = 0; this.selectedRows.length > i; i++) {
        // 相同的去掉
        idList.push(this.selectedRows[i].uuid)
      }
      this.loading = true
      deleteUsers(idList).then(res => {
        this.loading = false
        this.getData()
      })
    },
    exportExcel () {
      this.$refs.tables.exportCsv({
        filename: `table-${(new Date()).valueOf()}.csv`
      })
    },
    getData (searchObj) {
      this.loading = true
      if (typeof searchObj === 'undefined') {
        searchObj = {}
      }
      // 加上部门选择条件
      if (this.deptCode !== '' || this.deptCode !== null) {
        searchObj.deptCode = this.deptCode
      }
      getUsers(this.page.current, this.page.pageSize, searchObj).then(res => {
        this.arrangeDataToTable(res.data.data)
        this.loading = false
      }).catch(e => {
        this.loading = false
      })
    },
    getDataByChangeSize (index) {
      this.page.pageSize = index
      this.getData()
    },
    getDataOnSearch (searchObj) {
      this.page.current = 1
      this.getData(searchObj)
    },
    // 显示当前行数据
    showCurrentRow (row) {
      this.currentRow = row
      this.showCurrentRowFlag = true
    },
    // 单行选中
    onSelect (selection, row) {
      this.selectedRows = selection
      console.log(this.selectedRows)
    },
    onSelectCancel (selection, row) {
      this.selectedRows = selection
      console.log(this.selectedRows)
    },
    onSelectAll (selection) {
      this.selectedRows = selection
      console.log(this.selectedRows)
    },
    onSelectAllCancel (selection) {
      this.selectedRows = selection
      console.log(this.selectedRows)
    },
    onSelectionChange (selection) {
    },
    onSortChange (column, key, order) {
    },
    onFilterChange (row) {
    },
    onRowClick (row, index) {
    },
    onRowDblclick (row, index) {
    },
    onExpand (row, status) {
      this.$emit('on-expand', row, status)
    },
    async onSaveEdit (params) {
      this.loading = true
      const key = params.column.key
      // Object.assign(params.row, { key : params.value})
      this.$set(params.row, key, params.value)
      await updateUser(params.row)
      // if (ret.)
      this.loading = false
    },
    onUpdate (row) {
      this.drawerTitle = '编辑'
      this.operation = 'edit'
      if (row.roleCode === null) row.roleCode = []
      // 如果不修改，则传origin 代表不修改密码
      row.password = 'origin'
      this.formData = row
      console.log(this.formData)
      this.onCreateFlag = true
    },
    doUpdate () {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          // this.$Message.success('Success!')
          updateUser(this.formData).then(res => {
            if (res.data.code === 200) {
              alert('更新成功!')
              this.resetFormData()
              this.getData()
            }
          }).catch(e => {
            console.log(e)
            // this.$Message.error(e.data.message)
          })
        } else {
          this.$Message.error('请按要求填写!')
        }
      })
    },
    onCreate () {
      this.drawerTitle = '新增'
      this.operation = 'create'
      this.onCreateFlag = true
    },
    doCreate () {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          // this.$Message.success('Success!')
          addUser(this.formData).then(res => {
            if (res.data.code === 200) {
              alert('新增成功!')
              this.resetFormData()
              this.getData()
            }
          })
        } else {
          this.$Message.error('请按要求填写!')
        }
      })
    },
    resetFormData () {
      this.formData = {
        realName: '',
        nickname: '',
        loginName: '',
        phone: '',
        email: '',
        roleCode: [],
        description: ''
      }
    },
    // 装配返回数据到页面实体中
    arrangeDataToTable (data) {
      this.tableData = data.content
      this.page.current = data.pageNum
      this.page.pageSize = data.pageSize
      this.page.total = data.totalNumber
      this.page.totalPage = data.totalPage
    }
  },
  watch: {
    'formData.deptCode': {
      handler: function (val) {
        const deptCode = val
        PositionApi.all(deptCode).then(res => {
          this.positionList = res.data.data
        })
      }
    },
    'positionList': {
      handler: function (val) {
        // 装载显示的职位列表
        this.selectPostionList = []
        if (val instanceof Array && val.length > 0) {
          let tmpList = []
          val.map(item => {
            const cell = {
              value: item.code,
              label: item.positionName
            }
            tmpList.push(cell)
          })
          this.selectPostionList = tmpList
        }
      }
    },
    // 'roleList': {
    //   handler: function (val) {
    //     // 装载显示的职位列表
    //     this.selectRoleList = []
    //     if (val instanceof Array && val.length > 0) {
    //       let tmpList = []
    //       val.map(item => {
    //         const cell = {
    //           value: item.code,
    //           label: item.positionName
    //         }
    //         tmpList.push(cell)
    //       })
    //       this.selectRoleList = tmpList
    //     }
    //   }
    // },
    deptCode (val) {
      if (val !== null || val !== '') {
        this.getData({})
      }
    }
  },
  mounted () {
    // 获取所有用户列表
    getUsers().then(res => {
      this.arrangeDataToTable(res.data.data)
    })
    // 获取所有部门列表
    DeptApi.list().then(res => {
      const list = res.data.data
      this.deptList = list
    })
    // 获取所有角色列表
    RoleApi.all().then(res => {
      const list = res.data.data
      this.roleList = list
    })
  }
}
</script>

<style>
.demo-drawer-profile {
    font-size: 14px
}

.demo-drawer-profile .ivu-col {
    margin-bottom: 12px
}

</style>
